﻿using System;
using System.Collections.Generic;
using System.Text;
using MediatR;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Invoice;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Casamiel.Domain;
using Newtonsoft.Json;
using Microsoft.Extensions.Options;
using Casamiel.Common;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class GetOrderInvoiceInvoiceInfoByOrderCodeCommandHandler : BaseCommandHandler, IRequestHandler<GetOrderInvoiceInvoiceInfoByOrderCodeCommand, BaseResult<OrderInvoiceInformationRsp>>
    {
        private readonly IOrderBaseRepository _orderBaseRepository;
        private readonly IErrorLogRepository _errorLogRepository;
        public GetOrderInvoiceInvoiceInfoByOrderCodeCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOrderBaseRepository orderBaseRepository, IOptionsSnapshot<CasamielSettings> casamielSettings
            , IErrorLogRepository errorLogRepository) : base(netICService, httpClientFactory, casamielSettings)
        {
            _orderBaseRepository = orderBaseRepository;
            _errorLogRepository = errorLogRepository;
        }
        public async Task<BaseResult<OrderInvoiceInformationRsp>> Handle(GetOrderInvoiceInvoiceInfoByOrderCodeCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var orderentity = await _orderBaseRepository.GetByOrderCodeAsync<ICasaMielSession>(request.OrderCode).ConfigureAwait(false);
            if (orderentity != null && !string.IsNullOrEmpty(orderentity.InvoiceUrl))
            {
                var data = new { appToken = "bd481f06d2e19accab48965ada3b8f14d66d02b78b345d67908e4dc8f9d8860aefe0ad391d8963586632c4cba89bf64a", qrCode = orderentity.InvoiceUrl };
                var result = await PostAsync<ICResult>("api/NuoNuoAPI/ElectronicInvoiceAPI/GetOrderInvoiceInformationByOrderno", JsonConvert.SerializeObject(data), "InvoiceApi").ConfigureAwait(false);
                if (result.code == 0)
                {
                    return new BaseResult<OrderInvoiceInformationRsp>(JsonConvert.DeserializeObject<OrderInvoiceInformationRsp>(result.content), 0, "");
                }
                else
                {
                    return new BaseResult<OrderInvoiceInformationRsp>(null, result.code, result.msg);
                }
            }
            else
            {
                return new BaseResult<OrderInvoiceInformationRsp>(null, 999, "不可开票");
            }
        }
    }
}
